<template>
  <div class="business">
    <div class="title">外勤打卡</div>

    <div class="opes">
      <el-button size="small" @click="drawer = true">发起新的</el-button>
      <!-- headers 设置上传请求头 -->
      <!-- data 上传请求需要携带的参数 -->
      <!-- action 上传地址 -->
      <!-- name 上传字段, 字段值必须是 excel -->

      <!-- on-success 文件上传成功时的回调 -->
      <el-upload
        :show-file-list="false"
        :on-success="onSuccess"
        class="upload"
        :headers="headers"
        :data="{userid:userinfo._id}"
        name="excel"
        action="/api/business/import">
        <el-button size="small" >导入</el-button>
      </el-upload>
      
      <el-button size="small" > 
        <el-link :href="'/api/business/download?userid='+userinfo._id">导出</el-link> 
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      border
      :data="businesslist"
      style="width: 100%">
      <el-table-column
        prop="_id"
        label="编号"
        show-overflow-tooltip
        width="180">
      </el-table-column>
      <el-table-column
        prop="status"
        :formatter="formater_status"
        label="当前流程状态">
      </el-table-column>
      <el-table-column
        prop="name"
        label="申请人">
      </el-table-column>
      <el-table-column
        prop="reason"
        label="出差是由">
      </el-table-column>
      <el-table-column
        prop="starttime"
        label="出发日期"
        :formatter="formater_time"
        width="180">
      </el-table-column>
      <el-table-column
        prop="endtime"
        label="返回日期"
        :formatter="formater_time"
        width="180">
      </el-table-column>
      <el-table-column
        prop="days"
        label="出差总天数">
      </el-table-column>
      <el-table-column
        label="操作">
        <template slot-scope="scope">
          <!-- scope.row 当前行的 数据对象 -->
          <!-- scope.$index 当前行的 数据对象的索引 -->
          <el-button
            @click.native.prevent="deleteRow(scope.row._id)"
            type="danger"
            size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
      
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      @current-change="handleCurrentChange"
      :total="total">
    </el-pagination>

    <!-- 抽屉 -->
    <el-drawer
      :visible.sync="drawer">
      <el-form 
        :model="ruleForm" 
        status-icon 
        :rules="rules" 
        ref="ruleForm" 
        label-width="100px" 
        class="business-box">
        <h3 class="title">出差申请</h3>
        <el-form-item label="申请人" prop="name">
          <el-input type="text" v-model="ruleForm.name" autocomplete="off" placeholder="申请人"></el-input>
        </el-form-item>

        <el-form-item label="出差事由" prop="reason">
          <el-input type="textarea" v-model="ruleForm.reason" autocomplete="off" placeholder="出差事由"></el-input>
        </el-form-item>

        <el-form-item label="出发日期" prop="starttime">
          <el-date-picker
            v-model="ruleForm.starttime"
            type="date"
            placeholder="选择出发日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="返回日期" prop="endtime">
          <el-date-picker
            v-model="ruleForm.endtime"
            type="date"
            placeholder="选择返回日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="出差总天数" prop="days">
          <el-input type="text" v-model="ruleForm.days" autocomplete="off" placeholder="出差总天数"></el-input>
        </el-form-item>

        <el-form-item class="form-footer">
          <el-button type="primary" @click="submitForm()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { mapState } from 'vuex'
import {business_add,business_list,business_delete} from '../../utils/api'

export default {
  data(){
    var validateName= (rule, value, callback) => {
      if ( value.length < 2 ) {
        callback(new Error('请输入正确的申请人姓名'));
      } else {
        callback();
      }
    };
    var validateReason = (rule, value, callback) => {
      if ( !value ) {
        callback(new Error('请输入出差事由'));
      } else {
        callback();
      }
    };
    var validateStarttime = (rule, value, callback) => {
      if ( !value ) {
        callback(new Error('请选择出发日期'));
      } else {
        callback();
      }
    };
    var validateEndtime = (rule, value, callback) => {
      if ( !value || (new Date(this.ruleForm.starttime) - new Date(value)) > 0 ) {
        this.ruleForm.days = 0;
        callback(new Error('请选择返回日期'));
      } else {
        //计算总天数
        this.ruleForm.days = ( new Date(value) - new Date(this.ruleForm.starttime) ) / (24*60*60*1000) + 1;
        callback();
      }
    };
    var validateDays = (rule, value, callback) => {
      if ( Number(value) < 1 ) {
        callback(new Error('请输入出差总天数'));
      } else {
        callback();
      }
    };

    return {
      headers:{Authorization:'Bearer ' + localStorage.getItem('token')},
      drawer:false,//控制抽屉组件是否显示
      total:0,//出差申请总数
      page:1,//页码
      businesslist:[
        // {
        //   _id:'1',
        //   status:0,
        //   name:'李煜',
        //   reason:'出差给客户解决问题',
        //   starttime:'2022-8-22',
        //   endtime:'2022-8-23',
        //   days:1
        // },
        // {
        //   _id:'2',
        //   status:0,
        //   name:'李煜',
        //   reason:'出差给客户解决问题',
        //   starttime:'2022-8-22',
        //   endtime:'2022-8-23',
        //   days:1
        // },
      ],
      ruleForm:{
        name: this.$store.state.userinfo.name ,
        reason:'',
        starttime:'',
        endtime:'',
        days:0
      },
      rules: {
        name: [
          //validator 验证器 , trigger 触发器
          { validator: validateName, trigger: 'blur' }
        ],
        reason: [
          { validator: validateReason, trigger: 'blur' }
        ],
        starttime: [
          { validator: validateStarttime, trigger: 'blur' }
        ],
        endtime: [
          { validator: validateEndtime, trigger: 'blur' }
        ],
        days: [
          { validator: validateDays, trigger: 'blur' }
        ],
      }
    }
  },
  mounted(){
    business_list({ userid: this.userinfo._id ,page:1 }).then((res)=>{
      this.businesslist = res.data.list;
      this.total = res.data.total;
    })
  },
  computed:{
    ...mapState(['userinfo'])
  },
  methods:{
    submitForm(){
      this.$refs.ruleForm.validate((valid)=>{
        if( valid ){
          business_add( {userid: this.userinfo._id ,...this.ruleForm }).then((res)=>{
            if( res.data.code == 200 ){
              this.$message.success(res.data.msg);
              this.drawer = false;//隐藏抽屉
            }else{
              this.$message.error(res.data.msg);
            }
          })

        }else{
          console.log('验证失败');

        }
      })
    },
    formater_status(row, column, cellValue, index){
      return cellValue == 0 ? '待审批' : '已通过';
    },

    formater_num(num){
      return num < 10 ? '0'+num : num;
    },

    formater_time(row, column, cellValue, index){
      var d = new Date( cellValue );
      return `${d.getFullYear()}-${ this.formater_num( d.getMonth()+1 ) }-${ this.formater_num( d.getDate() ) }` ;
    },
    handleCurrentChange(val){
      this.page = val; //保存页码
      //请求对应页码的数据
      business_list({ userid: this.userinfo._id ,page:val }).then((res)=>{
        this.businesslist = res.data.list;
      })
    },
    deleteRow(id){
      //删除对应id的 出差申请
      business_delete({userid: this.userinfo._id , id ,page: this.page }).then((res)=>{
        this.businesslist = res.data.list;
        this.total = res.data.total;
      })
    },
    onSuccess(res){
      if( res.code == 200 ){
        this.$message.success(res.msg);
      }else{
        this.$message.error(res.msg);
      }
    }
  }
}
</script>

<style lang='scss'>
.opes{
  margin: 20px 0;
  display: flex;
  .upload{
    margin: 0 20px;
  }
}
.business-box{
  padding: 20px;
  .title{
    margin-bottom: 20px;
  }
}
.pagination{
  margin-top: 20px;
}
</style>